package com.oocl.o2o.merchant.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;

import com.oocl.o2o.merchant.dao.MerchantDao;
import com.oocl.o2o.merchant.entity.FoodType;
import com.oocl.o2o.merchant.entity.Merchant;

@Repository
public class MerchantDaoImpl implements MerchantDao {
	@PersistenceContext
	private EntityManager em;

	@Override
	public Merchant add(Merchant t) {
		try {
			em.persist(t);
			return t;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public Merchant update(Merchant t) {
		try {
			t = em.merge(t);
			return t;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public Merchant delete(String id) {
		try {
			Merchant merchant = em.find(Merchant.class, id);
			em.remove(merchant);
			return merchant;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public Merchant findById(String id) {
		try {
			Merchant merchant = em.find(Merchant.class, id);
			return merchant;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public List<Merchant> findAll() {
		try {
			String jpql = "select m from Merchant m";
			TypedQuery<Merchant> query = em.createQuery(jpql, Merchant.class);
			return query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public Merchant findByUsername(String username) {
		try {
			String jpql = "select m from Merchant m where m.username = :username";
			TypedQuery<Merchant> query = em.createQuery(jpql, Merchant.class);
			return query.setParameter("username", username).getSingleResult();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public Merchant findByUsernameAndPassword(String username, String password) {
		try {
			String jpql = "select m from Merchant m where m.username = :username and m.password = :password";
			TypedQuery<Merchant> query = em.createQuery(jpql, Merchant.class);
			return query.setParameter("username", username).setParameter("password", password).getSingleResult();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
